package com.coder.rental.security;

import com.coder.rental.entity.Permission;
import com.coder.rental.entity.User;
import com.coder.rental.service.IPermissionService;
import com.coder.rental.service.IUserService;
import jakarta.annotation.Resource;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * @author: zhanglin
 * @description:  重写loadUserByUsername方法，返回UserDetails对象，对象中包含用户的权限列表，用户详情服务
 * @date 2025/3/22
 */
@Component
public class CustomerUserDetailsService implements UserDetailsService {
    /*
    * 需要使用到的是实体类中的User，需要在User中去实现UserDetails接口
    * */
    @Resource
    private IUserService userService;

    @Resource
    private IPermissionService permissionService;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据username到数据库中查询
        User user = userService.selectByUsername(username);
        if(user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        /*
        * 用户登录，查询用户权限列表
        * */
        List<Permission> permissions = permissionService.selectPermissionListByUserId(user.getId());
        user.setPermissionList(permissions);
        /*
        * 通过stream流处理，将权限对象转换为权限字符串列表，采用链式调用
        * filter(Objects::nonNull)是获取到的对象不为空
        * */
        List<String> list = permissions.stream().filter(Objects::nonNull)
                .map(Permission::getPermissionCode)
                .filter(Objects::nonNull)
                .toList();
        /*
        * AuthorityUtils.createAuthorityList(array)传入的参数是array字符串数组
        * 将列表list转换为字符串数组，使用list.size()作为参数创建一个新的字符串数组
        * 调用toArray方法将列表中的元素复制到新数组
        * 将字符串array转换为一个GrantedAuthority类型的列表
        * GrantedAuthority是一个接口，代表用户拥有的权限
        * */
        String[] array = list.toArray(new String[list.size()]);
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(array);
        //为user对象设置权限列表，将之前创建好的GrantedAuthority赋值给user对象的权限属性
        user.setAuthorities(authorityList);
        System.out.println(user);
        return user;
    }
}
